import re
import sys
import os
import platform


def Jvaw_to_cpp(code):
    # 0. 替换所有 elif 为 else if
    code = code.replace("elif", "else if")
    # 1. 移除注释
    code = re.sub(r"//.*?$|/\*.*?\*/", "", code, flags=re.DOTALL | re.MULTILINE)
    # 2. 处理空行
    code = '\n'.join(line for line in code.split('\n') if line.strip())
    # 3. 替换单引号为双引号
    code = code.replace("'", '"')
    # 4. 自动添加分号（仅处理变量声明）
    lines = code.split('\n')
    processed_lines = []
    for line in lines:
        stripped = line.strip()
        if not stripped:
            continue
        # 识别控制结构
        if any(line.strip().startswith(kw) for kw in ["for", "if", "while", "else if", "else"]):
            processed_lines.append(line)
        # 仅处理变量声明（int a 或 int b=...）
        elif re.match(r'^int\s+[a-zA-Z_][a-zA-Z0-9_]*(?:\s*=\s*[^{;]+)?', stripped):
            processed_lines.append(line + ";")
        else:
            processed_lines.append(line)
    code = '\n'.join(processed_lines)
    # 5. 处理 print 和 printn（确保只添加一次分号）
    def process_print_params(params):
        in_quote = False
        quote_char = None
        result = []
        for c in params:
            if c in ('"', "'"):
                in_quote = not in_quote
                quote_char = c
            if c == ',' and not in_quote:
                result.append('<<')
            else:
                result.append(c)
        return ''.join(result)
    list_code = code.split('\n')
    for i in range(len(list_code)):
        if "print(" in list_code[i]:
            list_code[i] = re.sub(
                r'print\((.*?)\)',
                lambda m: f'cout<<{process_print_params(m.group(1))};',
                list_code[i]
            )
        elif "printn(" in list_code[i]:
            list_code[i] = re.sub(
                r'printn\((.*?)\)',
                lambda m: f'cout<<{process_print_params(m.group(1))}<<endl;',
                list_code[i]
            )
        elif "input(" in list_code[i]:
            list_code[i] = re.sub(
                r'input\((.*?)\)',
                lambda m: f'cin>>{m.group(1)};',
                list_code[i]
            )
    # 6. 处理 for 循环
    for i in range(len(list_code)):
        line = list_code[i].strip()
        # 匹配 for 循环结构
        match = re.match(r'^for\s+(\w+)\s+(\S+)\s+(\S+)\s+(\S+)\s*(\{?)\s*$', line)
        if match:
            var, start, end, step, brace = match.groups()
            # 强制统一生成标准结构
            list_code[i] = f'for(int {var}={start}; {var}<={end}; {var}+={step}) {{'
    # 7. 构建最终的 C++ 代码
    code = (
        "#include<bits/stdc++.h>\n"
        "using namespace std;\n"
        "int main(){\n" +
        "\n".join(list_code) +
        "\nreturn 0;\n}"
    ).replace("};", ";").replace("{;", "{").replace("{) {","){").replace("++\n","++;\n")
    return code


# -2. 自动将 cpp 编译
def auto_compile(cpp_file, output_file):
    cpp_file_dir = os.path.dirname(os.path.abspath(cpp_file))
    output_file = os.path.join(cpp_file_dir, output_file)
    
    try:  # 读取编译器配置
        with open("gccconfig.config", "r") as file:
            gcc = file.read().strip()
    except FileNotFoundError:
        with open("gccconfig.config", "w") as file:
            file.write("g++")
        gcc = "g++"
    
    # 根据操作系统判断输出文件扩展名
    if platform.system() == "Windows":
        if not output_file.endswith(".exe"):
            output_file += ".exe"
    else:
        if not output_file.endswith(".out"):
            output_file += ".out"
    
    print(os.popen(f"{gcc} {cpp_file} -o {output_file}").read())

# -1. 传入命令
args = sys.argv
if len(args) < 2:
    print("Jvaw Helps\n\nCompile to cpp:\njavw JvawFile.jvaw\njavw JvawFile.jvaw -c\njavw JvawFile.jvaw -c CppFile.cpp\n\nCompile to executable file:\njavw JvawFile.jvaw -o\njavw JvawFile.jvaw -o OutputExecutableFile")
else:
    try:
        # Ensure the input file has the correct .jvaw extension
        if not args[1].endswith(".jvaw"):
            raise ValueError("Input file must have a .jvaw extension")
        
        with open(args[1], 'r') as infile:
            code = infile.read()
        
        cppcode = Jvaw_to_cpp(code)
        output_cpp_file = args[1].replace(".jvaw", ".cpp")
        
        if len(args) == 2:
            with open(output_cpp_file, 'w') as outfile:
                outfile.write(cppcode)
            print(f"Compiled to {output_cpp_file}")
        
        elif len(args) == 3:
            if args[2] == "-c":
                with open(output_cpp_file, 'w') as outfile:
                    outfile.write(cppcode)
                print(f"Compiled to {output_cpp_file}")
            elif args[2] == "-o":
                output_exe_file = output_cpp_file.replace(".cpp", ".exe")
                auto_compile(output_cpp_file, output_exe_file)
                print(f"Compiled to {output_exe_file}")
        
        elif len(args) == 4:
            if args[2] == "-c":
                with open(args[3], 'w') as outfile:
                    outfile.write(cppcode)
                print(f"Compiled to {args[3]}")
            elif args[2] == "-o":
                output_exe_file = args[3]
                with open(output_cpp_file, 'w') as outfile:
                    outfile.write(cppcode)
                auto_compile(output_cpp_file, output_exe_file)
                print(f"Compiled to {output_exe_file}")

    except FileNotFoundError:
        print(f"Error: The file {args[1]} was not found.")
    except IOError as e:
        print(f"Error: An IOError occurred - {str(e)}")
    except ValueError as e:
        print(f"Error: {str(e)}")
    except Exception as e:
        print(f"Unexpected error: {str(e)}")
